package cn.zj.note.view.event;

import cn.zj.note.todo.Record;
import cn.zj.note.todo.Todo;
import cn.zj.note.todo.TodoManager;
import cn.zj.note.util.DateUtil;
import cn.zj.note.view.RecordStage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

import java.time.LocalDate;

public class RecordEventHandler implements EventHandler<ActionEvent> {
    public enum TimeEnum {
        LAST_DAY, CUR_DAY, CUR_WEEK, CUR_HALF_YEAR
    }
    private String title;
    private TimeEnum timeEnum;

    public RecordEventHandler(String title, TimeEnum timeEnum) {
        this.title = title;
        this.timeEnum = timeEnum;
    }

    @Override
    public void handle(ActionEvent actionEvent) {
        RecordStage recordStage = new RecordStage(title);
        recordStage.setContent(formatStr());
        recordStage.show();
    }

    private String formatStr(){
        StringBuilder sb = new StringBuilder();
        for (Todo todo : TodoManager.getInstance().getTodos()) {
            boolean firstRecord = true;
            for (Record record : todo.getRecords()) {
                if(IsMatchDate(record.getCreateTime().toLocalDate())){
                    if(firstRecord){
                        sb.append("\r\n").append(todo.getTitle()).append("\r\n");
                        firstRecord = false;
                    }
                    sb.append(record.getContent()).append("\r\n");
                }
            }
        }
        return sb.toString();
    }

    private boolean IsMatchDate(LocalDate localDate) {
        switch (timeEnum){
            case LAST_DAY:
                return DateUtil.curLocalDate().plusDays(-1).equals(localDate);
            case CUR_DAY:
                return DateUtil.curLocalDate().equals(localDate);
            case CUR_WEEK:
                return DateUtil.isSameWeek(localDate,DateUtil.curLocalDate());
            case CUR_HALF_YEAR:
                return true;
        }
        return false;
    }
}
